package com.studentstreet;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.studentstreet.adapter.CartAdapter;
import com.studentstreet.entities.CartEntity;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.dbhelper.OrderDBHelper;

/**
 * @author likebamboo
 * 
 */
public class CartActivity extends ListActivity implements OnGestureListener {
	// Title标题
	private TextView titleText;
	// Login Button登录按钮
	private Button login_bt;
	// 头部左边的按钮
	private ImageButton backImgBt = null;

	// 购物车的ListView
	private ListView cartListView = null;
	// ListView适配器.
	private CartAdapter adapter = null;
	// ListView更新标识。
	private final static int LIST_UPDATE = 1;
	// 移除商品的小pop
	private PopupWindow popupWindow = null;
	// 移除商品按钮
	private Button deleteButton = null;
	// 下达订单按钮
	private Button orderButton = null;

	// 去购物
	private Button goShoppingBt = null;

	private OrderDBHelper dbHelper = null;
	private List<CartEntity> cartList = null;
	// 用户名
	private String userName = "";

	// OEM++ 侧边栏菜单的手势效果 @ 2013-1-15
	private GestureDetector gestureDetector;

	// OEM--

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.cart);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);

		// OEM++ liwt@2013-1-15
		gestureDetector = new GestureDetector(this);
		// OEM--

		// 初始化数据库工具类对象
		dbHelper = new OrderDBHelper(this);
		// 初始化购物车实体对象
		cartList = new ArrayList<CartEntity>();

		// 初始化头部
		initHeader();
		// 初始化布局
		cartListView = getListView();
		// 去下单按钮
		orderButton = (Button) findViewById(R.id.cart_buy);
		// 去购物按钮（针对购物车为空的情况）
		goShoppingBt = (Button) findViewById(R.id.cart_go_shopping);

		orderButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 下达订单，
				Intent intent = new Intent(CartActivity.this,
						OrderActivity.class);
				startActivity(intent);
			}
		});

		goShoppingBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 回到首页，
				Intent intent = new Intent(CartActivity.this,
						MainActivity.class);
				startActivity(intent);
				finish();
			}
		});
	}

	// 显示移除商品的popUpWindow
	private void showPopup(View parent, int position) {
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的宽度的一半
		int width = windowManager.getDefaultDisplay().getWidth();
		int height = windowManager.getDefaultDisplay().getHeight();
		if (popupWindow == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = layoutInflater
					.inflate(R.layout.cart_delete_popup, null);
			deleteButton = (Button) view.findViewById(R.id.cart_delete);
			// 创建一个PopuWidow对象
			popupWindow = new PopupWindow(view, width / 3, height / 7);
		}
		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的宽度的一半
		int xPos = width - popupWindow.getWidth() / 2;
		popupWindow.showAsDropDown(parent, xPos, 0);
		// 这条语句不可放在if(popupWindown==null)中，要不然当popupWindow！=null时就不会执行了，那么就会报错。
		// 如果一定要放在里面，那么必须将popupWindow声明为这个方法的局部变量而不是类成员变量。
		deleteButton.setOnClickListener(new DeleteListener(position));
	}

	private void initHeader() {
		// 返回按钮
		backImgBt = (ImageButton) findViewById(R.id.header_imgBt);
		// 头部中间的标题
		titleText = (TextView) findViewById(R.id.title);
		// 登录按钮
		login_bt = (Button) findViewById(R.id.login_bt);
		// 返回按钮
		backImgBt.setImageResource(R.drawable.back);
		backImgBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		// 头部中间的标题
		titleText.setText(getResources().getString(R.string.cart));
		// 登录按钮
		login_bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 显示登录对话框
				Intent intent = new Intent(CartActivity.this, LoginDialog.class);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 获得用户名
		PreferenceTools prefTools = new PreferenceTools(this);
		if (!prefTools.isLogin()) {
			return;
		}
		// 登录后修改登录按钮上的text
		String userNameTemp = prefTools.getUserName();
		// 当用户名有更新时候
		if (!userNameTemp.equals(userName)) {
			userName = userNameTemp;
			// 修改用户名
			if (!userName.equals("")) {
				login_bt.setText(userName);
				// 去掉登录按钮文本右边的图标
				login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null,
						null, null);
			}
			// 创建(更新)适配器
			adapter = new CartAdapter(this, userName);
			cartListView.setAdapter(adapter);
			// 添加ListView的Item点击事件
			cartListView
					.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> adapter,
								View view, int postion, long arg3) {
							// 显示移除该商品的popUpWindow
							showPopup(view, postion);
						}
					});
		}
		// 启动数据查询线程
		Thread queryDataThread = new Thread(new QueryDataThread());
		queryDataThread.start();
	}

	// 查询数据库线程
	class QueryDataThread implements Runnable {

		@Override
		public void run() {
			// 查询数据库中的订单项信息
			cartList = dbHelper.getCart(userName);
			// 将数据添加到适配器中
			adapter.addCartList(cartList);
			Message msg = handler.obtainMessage();
			msg.what = LIST_UPDATE;
			handler.sendMessage(msg);
		}
	}

	// 移除商品的监听器
	class DeleteListener implements OnClickListener {
		private int position = 0;

		public DeleteListener(int position) {
			this.position = position;
		}

		@Override
		public void onClick(View v) {
			// 让popupwindow 消失
			popupWindow.dismiss();
			// 如果移除数据不成功，直接返回null；
			if (!adapter.removeCart(position)) {
				return;
			}
			// 移除成功。发送一个消息
			Message msg = handler.obtainMessage();
			msg.what = LIST_UPDATE;
			handler.sendMessage(msg);
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LIST_UPDATE:
				// 通知ListView有更新
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	// OEM++手势滑动 李文涛@2013-1-15
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	/**
	 * 用户按下触摸屏、快速移动后松开
	 */
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.i("MyGesture", "onFling");

		final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;
		if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling right
			LeftMenu.prepare(CartActivity.this, R.id.cart_layout);
			startActivity(new Intent(CartActivity.this, LeftMenu.class));
			overridePendingTransition(0, 0);
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	public boolean onTouch(View v, MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	/**
	 * 解决ScrollView后不执行左右移动监听事件OnGestureListener
	 * 在Activity中添加ScrollView实现滚动activity的效果后，activity的滑动效果却无法生效了
	 * 原因是因为activity没有处理滑动效果，重写以下方法即可解决。
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		gestureDetector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}
	
	//OEM--

	// OEM++ 2013-02-27 监听菜单按钮事件，实现与手势相同的滑动效果
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		LeftMenu.prepare(CartActivity.this, R.id.cart_layout);
		startActivity(new Intent(CartActivity.this, LeftMenu.class));
		overridePendingTransition(0, 0);
		return false;
	}
	// OEM--
}
